package edu.zju.gis.dldsj.utils;

import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 写单个文件的工具类
 *
 * @author HLS
 */
public final class MetaDataFileOperator {
    private static final Logger log = LoggerFactory.getLogger(MetaDataFileOperator.class);

    public static String readFile(String fileName) {
        JSONObject json = null;
        File file = new File(fileName);
        if (!file.exists()) {
            log.info("Read File Fail, File not exist");
            return "";
        }

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            //整个文件就一行
            json = new JSONObject(br.readLine());
            br.close();
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }
        return json.toString();
    }


    public static String writeFile(String fileName, String content) {

        File file = new File(fileName);
        if (file.exists()) {
            try {
                throw new Exception("File Already Exists");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write((content + "\r\n").getBytes("utf-8"));
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileName;
    }
}
